const multiparty = require('multiparty')
const { resolve, join } = require('path')
const fs = require('fs')
const axios = require('axios')
let { bookmark } = require('../config/config');

module.exports = {
  index(req, resp) {
    console.log(`=====`,)
    // 重新定向
    // resp.redirect(301, '/pages/folder.html');
    resp.redirect(200, '/pages/folder.html');
    // resp.redirect(200, '/pages/手机版本-书签.html');
    // resp.render('index', {})
  },
  // 获取目录
  async getlist(req, resp) {
    let { git_url, header_, owner, repo, path, access_token, ref } = bookmark
    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token + '&ref=' + ref
    axios.get(url, {
      method: 'GET',
      headers: header_
    })
      .then(function (response) {
        // console.log('getlist', response.data)
        resp.send(JSON.stringify(response.data))
      });
  },
  // 获取文件Blob
  async getFileContent(req, resp) {
    let { path } = req.query
    // console.log(`path ====`, path)
    let { git_url, header_, owner, repo, access_token, ref } = bookmark

    path = path || ""
    // path = path || "bookmarks/2022-11-07"

    let url = git_url + '/v5/repos/' + owner + '/' + repo + '/contents/' + path + '?access_token=' + access_token

    axios.get(url, {
      method: 'GET',
      headers: header_
    })
      .then(function (response) {
        try {
          let info = JSON.parse(decodeURIComponent(atob(response.data['content'])))
          // console.log(`info`, info)
          let send = JSON.stringify(info[0]['children'][0]["children"])
          console.log(`获取书签成功`,)
          resp.send(send)
        } catch (e) {
          console.log(`获取书签 失败了`,)
          console.log('error', e)
          resp.send(JSON.stringify([]))
        }
      });
  },
}
